<template>
  <div class="page-controller">
    <FISearchForm
      class="box-radius2"
      ref="ruleFormRef"
      :id="`inqu_${tableId}`"
      :searchNum="getHasSearchValues(state.query)"
      v-model:form-value="state.query"
      :table-column="columns"
      :wrapperSpan="searchWrapperSpan"
      @submit="searchFn"
    >
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="formEname" label="页面编码">
          <FIInput v-model="state.query.formEname" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem name="buttonEname" label="按钮编码">
          <FIInput v-model="state.query.buttonEname" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem name="isAuth" label="是否授权">
          <FISelect
            v-model="state.query.isAuth"
            valueCustom="value"
            :options="[
              { value: '1', label: '是' },
              { value: '0', label: '否' },
            ]"
            clearable
          />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem name="projectEname" label="前端项目">
          <FISelect
            v-if="arr2.length > 0"
            v-model="state.query.projectEname"
            valueCustom="value"
            :options="arr2"
            clearable
          />
        </FIFormItem>
      </el-col>

      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem name="moduleEname1" label="一级模块">
          <FIInput v-model="state.query.moduleEname1" clearable />
        </FIFormItem>
      </el-col>
    </FISearchForm>
    <div class="margin-bottom20"></div>
    <FITable
      ref="tableRef"
      class="box-radius2"
      title="按钮集"
      :id="`result_${tableId}`"
      :readonly="false"
      :data="state.dataList"
      primaryKey="buttonId"
      v-model:columns="columns"
      :isLoading="isTableLoading"
      insertable
      deletable
      :saveSuccessful="saveSuccessful"
      :pageConfig="pageConfig"
      @row-add-save="addRowSave"
      @table-refresh="searchFn"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-page-change="handleCurrentChange"
      @action-click="handleAction"
      @row-delete="deleteRow"
    >
      <!-- <template #headerBtn>
        <FIPopconfirmBtn
          title="您是否确认删除选中数据吗？"
          buttonText="删除"
          beforePopText="请选择一条数据"
          :btn-binds="{ border: true, prefixIcon: 'icon-shanchu' }"
          :isVisible="!!checkedRows.length"
          @confirm="deleteRow"
        >
        </FIPopconfirmBtn>
      </template> -->
      <template #apiModule1="{ scope }">
        <FISelect
          v-if="scope.row.isSelected"
          v-model="scope.row.apiModule1"
          :display-key="['value', 'label']"
          :options="arr3"
          clearable
        />
        <span v-else>{{ scope.row.apiModule1 }}</span>
      </template>
      <template #empty> 暂无数据 </template>
    </FITable>
  </div>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref } from 'vue'
import FISearchForm from '@/components/FISearchForm.vue'
import FIFormItem from '@/components/FIFormItem.vue'
import FIInput from '@/components/FIInput.vue'
// import FIPopconfirmBtn from '@/components/FIPopconfirmBtn.vue'
import FITable from '@/components/FITable/index.vue'
import FISelect from '@/components/FISelect/index.vue'
import { apiRequestPost } from '@/api/globalApi.js'
import { ElMessage } from 'element-plus'
import { useMessage } from '@/hooks/message'
import type { PageConfig, Column } from '@/types/components'
import { initSearchData, getHasSearchValues } from '@/utils/common'
import { getQueryTableCache } from '@/utils/cacheUtils'
import { apiGetfrontPrjMaint, apiGetlistAllModule1 } from '@/api/configEnvMaint/index.ts'
import { useRoute } from 'vue-router'
import { getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance() // 获取当前组件实例上下文
const tableRef = ref(null)

const route = useRoute()
const searchWrapperSpan = 8
const isTableLoading = ref(false)
// 页面编码
const tableId = 'buttonMaint'
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
const state = reactive({
  query: {
    formEname: '',
    buttonEname: '',
    projectEname: '',
    moduleEname1: '',
    isAuth: '',
    dynamicParams: [],
    orderbyParams: [],
    current: 1,
    size: 10,
  },
  dataList: [],
})
const pageConfig: PageConfig = reactive({
  total: 0,
  currentPage: 1,
})

const columns: Column = reactive([
  {
    label: '页面编码',
    prop: 'formEname',
    align: 'center',
    width: '140',
    queryName: '',
    editable: true,
    readonly: true,
    // sortable: true,
    // filterable: true,
    modelValue: { inputValue: '' },
    required: true,
    editType: 'input',
  },
  {
    label: '区域ID',
    prop: 'regionId',
    align: 'center',
    width: '140',
    queryName: '',
    editable: true,
    // sortable: true,
    // filterable: true,
    modelValue: { inputValue: '' },
    editType: 'input',
    editConfig: {
      rules: { formEname: [{ required: false, message: '请输入区域ID', trigger: 'blur' }] },
    },
  },
  {
    label: '按钮编码',
    prop: 'buttonEname',
    queryName: '',
    align: 'center',
    width: '150',
    editType: 'input',
    editable: true,
    readonly: true,
    // filterable: true,
    // sortable: true,
    required: true,
    modelValue: { inputValue: '' },
  },
  {
    label: '按钮名称',
    prop: 'buttonCname',
    align: 'center',
    width: '180',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    editable: true,
    modelValue: { inputValue: '' },
    // filterable: true,
    // sortable: true,
    required: true,
    sortValue: '',
  },

  {
    label: '按钮描述',
    prop: 'buttonDesc',
    align: 'center',
    width: '180',
    // filterable: false,
    // sortable: false,
    editable: true,
    modelValue: { inputValue: '' },
    editType: 'input',
  },
  {
    label: '是否授权',
    prop: 'isAuth',
    align: 'center',
    width: '130',
    editable: true,
    // filterable: true,
    // sortable: true,
    editType: 'select',
    modelValue: [],
    required: true,
    editConfig: {
      options: [
        { value: '1', label: '是' },
        { value: '0', label: '否' },
      ],
      selectBinds: {
        multiple: false,
        valueCustom: 'value',
      },
    },
  },
  {
    label: '图标',
    prop: 'uri',
    align: 'center',
    width: '130',
    editType: 'input',
    editable: true,
  },
  // {
  //   label: '后端项目一级模块',
  //   prop: 'apiModule1',
  //   align: 'center',
  //   width: '200',
  //   editable: true,
  //   filterable: true,
  //   sortable: true,
  //   modelValue: { inputValue: '' },
  //   editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  // },
  {
    label: '接口路径',
    prop: 'apiUrl',
    align: 'center',
    width: '130',
    editable: true,
    // filterable: true,
    // sortable: true,
    modelValue: { inputValue: '' },
    editType: 'input',
  },
  {
    label: '接口模块',
    prop: 'apiModule1',
    align: 'center',
    width: '130',
    editable: true,
    // filterable: true,
    // sortable: true,
    modelValue: { inputValue: '' },
    editType: 'input',
  },
  {
    label: '创建人',
    prop: 'recCreator',
    align: 'center',
    width: '120',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '创建时间',
    prop: 'recCreateTime',
    align: 'center',
    width: '160',
    editType: 'time-picker', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '修改人',
    prop: 'recRevisor',
    align: 'center',
    width: '120',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '修改时间',
    prop: 'recReviseTime',
    align: 'center',
    width: '160',
    editType: 'date-picker', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  // {
  //   label: '',
  //   prop: 'action',
  //   actionConfig: [
  //     { id: 'delete', type: 'delete' },
  //     { id: 'add', type: 'add' },
  //   ],
  //   isCustomAction: true,
  // },
])

const checkedRows = ref([])
const handleSelectionChange = (e) => {
  checkedRows.value = e
}
const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  searchFn()
}
const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  searchFn('page')
}
const searchFn = (type?: string, columnsVal?: any) => {
  const obj = initSearchData(type, columnsVal, columns, state.query)
  state.query = obj.queryData
  columns.values = obj.columns
  if (type == 'page') {
    state.query.current = pageConfig.currentPage
  } else {
    pageConfig.currentPage = 1
    state.query.current = 1
  }

  isTableLoading.value = true
  if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
  const apiUrl = proxy.$Button_api('query', route.name)
  apiRequestPost(apiUrl, state.query)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        const tempArr = res.data.data.result
        // tempArr.forEach((item: any, index) => {
        //   item.dynamicActionConfig = [
        //     { id: 'delete', type: 'delete', hidden: true, disabled: true },
        //     { id: 'add', type: 'add', disabled: false },
        //   ]
        // })
        state.dataList = tempArr
        pageConfig.pageSize = Number(res.data.data.size)
        pageConfig.total = Number(res.data.data.count)
      } else {
        ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
const handleSave = () => {
  isTableLoading.value = true
  saveSuccessful.value = false
  const apiUrl = proxy.$Button_api('save', route.name)
  apiRequestPost(apiUrl, checkedRows.value)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        // saveSuccessful.value = true
        tableRef.value.clearSelection()
        searchFn()
      } else {
        ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
const deleteRow = () => {
  if (!checkedRows.value.length) {
    useMessage().warning('请选择一条数据')
    return
  }
  let ids = []
  Array.isArray(checkedRows.value) &&
    checkedRows.value.forEach((item: any) => {
      if (item?.buttonId) ids.push(item?.buttonId)
    })
  isTableLoading.value = true
  const apiUrl = proxy.$Button_api('delete', route.name)
  apiRequestPost(apiUrl, ids)
    .then((res) => {
      isTableLoading.value = false
      searchFn()
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
const ruleFormRef = ref(null)

const addRowSave = (data) => {
  handleSave(data, 'add')
}
const handleAction = (item, rowData) => {
  // this.$globalMethod('777')
}
const arr2 = ref([])
const getProjectname = () => {
  apiGetfrontPrjMaint().then((res) => {
    if (res.data.success) {
      Array.isArray(res.data.data) &&
        res.data.data.forEach((item) => {
          // item.label = item.moduleCname2
          item.label = `[${item.appCname}] ${item.appEname}`
          item.value = item.appEname
        })

      if (Array.isArray(res.data.data)) {
        const newArray = res.data.data.map((item) => ({
          label: `[${item.appEname}] ${item.appCname}`,
          value: item.appEname,
        }))
        // columns[3].editConfig.options = newArray
        // columns.editConfig.options = newArray
        // 在 DOM 更新后执行的操作
        arr2.value = newArray
      }
    }
  })
  // 如果是下拉框字段，触发接口获取选项
  //  this.fetchOptions(row旧值); // 根据旧值或上下文决定如何查询
}
const arr3 = ref([])
const getProjectname1 = () => {
  apiGetlistAllModule1().then((res) => {
    if (res.data.success) {
      Array.isArray(res.data.data) &&
        res.data.data.forEach((item) => {
          // item.label = item.moduleCname2
          item.label = item.moduleEname1
          item.value = item.moduleEname1
        })

      if (Array.isArray(res.data.data)) {
        const newArray = res.data.data.map((item) => ({
          label: item.moduleEname1,
          value: item.moduleEname1,
        }))
        // columns[3].editConfig.options = newArray
        // columns.editConfig.options = newArray
        // 在 DOM 更新后执行的操作
        arr3.value = newArray
      }
    }
  })
  // 如果是下拉框字段，触发接口获取选项
  //  this.fetchOptions(row旧值); // 根据旧值或上下文决定如何查询
}
onMounted(() => {
  getProjectname()
  getProjectname1()
  // 获取查询条件缓存
  const { cachedQuery, cachedColumns } = getQueryTableCache(route.path, tableId, state.query, columns.values)
  if (cachedQuery) state.query = cachedQuery
  if (columns) columns.values = cachedColumns
  searchFn()
})
</script>
<style lang="less" scoped></style>
